<?php
/**
 * Created by PhpStorm.
 * User: u
 * Date: 2018/12/18
 * Time: 15:06
 */
namespace common\logics\kq;

use Yii;
use common\services\kq\KqPayService;
use common\widgets\Tool;
use yii\base\BaseObject;

class KqPayLogic extends BaseObject implements IKqPay
{
    /** @var \common\sources\write\rechargerecord\RechargeRecordAccess $WRechargeRecordAccess **/
    private $WRechargeRecordAccess;
    /** @var \common\sources\read\rechargerecord\RechargeRecordAccess  $RRechargeRecordAccess **/
    private $RRechargeRecordAccess;

    public function init()
    {
        $this->RRechargeRecordAccess = Yii::$container->get("RRechargeRecordAccess");
        $this->WRechargeRecordAccess = Yii::$container->get("WRechargeRecordAccess");
        parent::init(); // TODO: Change the autogenerated stub
    }

    public function payAmount($data)
    {
        if(empty($data['uid'])){
            return Tool::returnJson([],401,"商家用户id不能为空");
        }
        if(empty($data['pay_type'])){
            return Tool::returnJson([],402,"充值方式不能为空");
        }
        if(empty($data['order_amount'])){
            return Tool::returnJson([],403,"充值金额不能为空");
        }
        if(!($data['pay_type'] == 1 || $data['pay_type'] == 2)){
            return Tool::returnJson([],405,"选择充值方式有误");
        }

        $kqPayService = new KqPayService();
        $arr = $kqPayService->pay($data);
        if(empty($arr['pay_url'])){
            return Tool::returnJson([],407,"第三方支付异常，请切换其他支付方式");
        }
        return Tool::returnJson($arr,200,"成功");
    }
    //银行卡业务处理
    public function payBank($data)
    {
        if(empty($data['uid'])){
            return Tool::returnJson([],401,"商家用户id不能为空");
        }
        if(empty($data['pay_type'])){
            return Tool::returnJson([],402,"充值方式不能为空");
        }
        if(empty($data['order_amount'])){
            return Tool::returnJson([],403,"充值金额不能为空");
        }
        if($data['pay_type'] != 3){
            return Tool::returnJson([],405,"选择充值方式有误");
        }
        if(empty($data['orderId']))
        {
            return Tool::returnJson([],406,"订单编号不能为空");
        }

        $kqPayService = new KqPayService();
        $arr = $kqPayService->payBank($data);
        return $arr;
    }
    //回调处理
    public function doNotify($data)
    {
        $kqPayService = new KqPayService();
        $result = $kqPayService->doNotify($data);
        $user = $this->RUserAccess->getUserById($_REQUEST['ext1']);
        $pay_status = 0;
        $rechar_str = '';
        if($_REQUEST['ext2'] == 1)
        {
            $rechar_str = '快钱-微信';
        }else if($_REQUEST['ext2'] == 2)
        {
            $rechar_str = '快钱-支付宝';
        }else if($_REQUEST['ext2'] == 3)
        {
            $rechar_str = '快钱-网银';
        }

        if($result['rtnOK'] == 1)
        {
            //回调成功之后的判断
            $recharge_record = $this->RRechargeRecordAccess->getRechargeRecord($_REQUEST['orderId']);
            if(empty($recharge_record))
            {
                $pay_status = 1;
                $trr = [
                    'uid' => $_REQUEST['ext1'],
                    'type' => $_REQUEST['ext2'],
                    'money' => number_format($_REQUEST['payAmount']/100,2,'.',''),
                    'merchant_order' => $_REQUEST['orderId'],
                    'pay_status' =>$pay_status,
                    'remark' => "充值金额 +".number_format($_REQUEST['payAmount']/100,2,'.',''),
                ];
                $res = $this->WRechargeRecordAccess->addRechargeRecord($trr);
                if($res)
                {
                    $user = $this->RUserAccess->getUserById($_REQUEST['ext1']);
                    if(!empty($user))
                    {
                        //邀请人 首次充值交易提醒
                        if($user['cumulate_recharge'] == 0)
                        {
                            $dd_url = Yii::$app->params['dd_kq_pay_recharge'];
                            $message = '';
                            if(isset($user['inviter_phone']) && !empty($user['inviter_phone']))
                            {
                                $message = $user['phone']."首充". number_format($_REQUEST['payAmount']/100,2,'.','')."元，交易编号".$_REQUEST['orderId'].",邀请人".$user['inviter_phone'];
                            }else
                            {
                                $message = $user['phone']."首充". number_format($_REQUEST['payAmount']/100,2,'.','')."元，交易编号".$_REQUEST['orderId'];
                            }
                            $param = array ('msgtype' => 'text','text' => array ('content' => $message),"at"=>["isAtAll" =>true]);
                            $data_string = json_encode($param);
                            $this->request_by_curl($dd_url, $data_string);
                        }

                        $balance = number_format($user['account_balace'] + ($_REQUEST['payAmount']/100),2,'.','');
                        $urr = [
                            'account_balace' => $balance,
                            'cumulate_recharge' => number_format($user['cumulate_recharge']+($_REQUEST['payAmount']/100),2,'.',''),
                            'uid' => $_REQUEST['ext1'],
                        ];
                        $this->WUserAccess->modifyUserBalance($urr);
                        //添加充值记录
                        $frr = [
                            'uid' => $_REQUEST['ext1'],
                            'income' => number_format($_REQUEST['payAmount']/100,2,'.',''),
                            'expend' => '0',
                            'surplus' => $balance,
                            'fund_type' => 1,
                            'tran_num' => $_REQUEST['orderId'],
                            'desc' => $rechar_str,
                            'is_back' => 1,
                            'remark' => '账号充值',
                            'operator' => "system",
                        ];
                        $this->WFundRecordAccess->addFundRecord($frr);
                    }
                }
            }

        }
        return $result['str'];
    }
    //
    private function request_by_curl($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }


    //检查是否支付成功
    public function checktOrderStatus($data)
    {
        if(empty($data['uid'])){
            return Tool::returnJson([],401,"商家用户id不能为空");
        }
        if(empty($data['orderId']))
        {
            return Tool::returnJson("商户订单编号不能为空");
        }
        //判断用户是否存在
        $user = $this->RUserAccess->getUserById($data['uid']);
        if(empty($user))
        {
            return Tool::returnJson([],5150,"用户不存在");
        }
        $rechargerecord = $this->RRechargeRecordAccess->getRechargeRecord($data['orderId']);
        if(empty($rechargerecord))
        {
            return Tool::returnJson([],405,"暂未找到对应的商户");
        }
        return Tool::returnJson($rechargerecord,200,"成功");
    }
}